import 'package:flutter/material.dart';
import 'package:flutter_wan_android/core/config/router.dart';
import 'package:flutter_wan_android/data/article/article_repository.dart';
import 'package:flutter_wan_android/data/banner/banner_repository.dart';
import 'package:flutter_wan_android/data/user/user_repository.dart';
import 'package:flutter_wan_android/feature/home/home_view_model.dart';
import 'package:provider/provider.dart';

import 'home/home_screen.dart';

class MainScreen extends StatefulWidget {
  const MainScreen({super.key});

  @override
  State<MainScreen> createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  int _index = 0;
  final _pageList = [
    ChangeNotifierProvider(
      create:
          (context) => HomeViewModel(
            context.read<BannerRepository>(),
            context.read<ArticleRepository>(),
          ),
      child: HomeScreen(),
    ),
    PersonScreen(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //IndexedStack 可使widget常驻内存，tab切换执行show/hide 不是 add/remove
      body: IndexedStack(index: _index, children: _pageList),
      bottomNavigationBar: _buildBottomNavigationBar(),
    );
  }

  /// BottomNavigationBar 基本样式还可以
  Widget _buildBottomNavigationBar() {
    return Theme(
      //只修改 BottomNavigationBar 的主题配置，
      //移除NavBar整体点击水波纹 和 BarItem点击水波纹效果
      data: Theme.of(context).copyWith(
        splashColor: Colors.transparent,
        highlightColor: Colors.transparent,
      ),
      child: BottomNavigationBar(
        currentIndex: _index,
        selectedFontSize: 12,
        backgroundColor: Colors.white,
        onTap: _handleBottomNavigation,
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: "首页"),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: "我的"),
        ],
      ),
    );
  }

  ///处理底部导航选中
  void _handleBottomNavigation(int index) async {
    bool loginState = await context.read<UserRepository>().getLoginState();
    if (!mounted) return; // 生命周期相关属性，表示当前widget是否已经 dispose，调用异步函数后setState的写法

    if (index == 1 && !loginState) {
      Navigator.pushNamed(context, AppPages.login);
      return;
    }

    setState(() {
      _index = index;
    });
  }
}

class PersonScreen extends StatelessWidget {
  const PersonScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Center(child: Text("PersonScreen hello world"));
  }
}
